package com.imti.mall.common.exception;

import com.imti.mall.common.domain.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 通用的异常处理器
 * */
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {

    /**
     * 处理后台数据校验异常
     * */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public CommonResult handlerBindException(BindException e){
        log.error(e.getMessage(),e);
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return CommonResult.validateFailed(message);
    }

    /**
     * 处理业务异常
     * */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public CommonResult handlerBusinessException(BusinessException e){
        log.error(e.getMessage(),e);
        if (e.getErrorCode() != null) {
            return CommonResult.failed(e.getErrorCode());
        }
        return CommonResult.failed(e.getMessage());
    }


    /**
     * 处理系统异常
     * */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public CommonResult handlerException(Exception e){
        log.error(e.getMessage(),e);
        return CommonResult.failed();
    }
}
